package syn_demo1;

public class SyncExample {
    private final Object blockLock = new Object();

    // synchronized 修饰实例方法，锁的是当前对象 this
    public synchronized void instanceMethod() {
        System.out.println(Thread.currentThread().getName() + " acquired lock on instance method");
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " released lock on instance method");
    }

    // synchronized 修饰静态方法，锁的是类对象 Class
    public static synchronized void staticMethod() {
        System.out.println(Thread.currentThread().getName() + " acquired lock on static method");
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " released lock on static method");
    }

    // synchronized 修饰代码块，锁的是指定的对象
    public void blockMethod() {
        synchronized (blockLock) { // 锁住 blockLock 对象
            System.out.println(Thread.currentThread().getName() + " acquired lock on block");
            try {
                Thread.sleep(1000); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " released lock on block");
        }
    }

    public static void main(String[] args) {
        SyncExample example1 = new SyncExample();
        SyncExample example2 = new SyncExample();



//        // 线程测试实例方法锁
//        new Thread(example1::instanceMethod, "Thread-1").start();
//        new Thread(example1::instanceMethod, "Thread-2").start(); // 不同对象，互不影响

//        // 线程测试静态方法锁
        // 线程1测试实例方法锁
//        Thread thread1 = new Thread(() -> {
//            staticMethod();
//        });
//
//        // 线程2测试实例方法锁
//        Thread thread2 = new Thread(() -> {
//            staticMethod();
//        });
//
//        thread1.start();
//        thread2.start(); // 静态方法锁相互阻塞
//
//

        // 线程1测试同步代码块锁
        Thread thread1 = new Thread(() -> {
            example1.blockMethod();
        });

        // 线程2测试同步代码块锁
        Thread thread2 = new Thread(() -> {
            example2.blockMethod();
        });

        thread1.start();
        thread2.start();
    }
}
